package com.zhiwei.msf.gateway.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zhiwei.msf.common.constant.CommonErrorConstants;
import com.zhiwei.msf.common.constant.ResultResponseMsg;
import com.zhiwei.msf.common.exception.BasePublishException;
import com.zhiwei.msf.gateway.dao.entity.UserInfo;
import com.zhiwei.msf.gateway.service.CaptchaService;
import com.zhiwei.msf.gateway.service.UserTokenService;
import com.zhiwei.msf.gateway.service.WhiteListService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * function 网关对外服务端口
 * author zhiwei.yang
 * time 2020-2-28-10:11
 */
@RestController
@RequestMapping("/gateway")
@Api(tags = "网关对外服务")
public class GatewayController {

    @Autowired
    private UserTokenService userTokenService;

    @Autowired
    private WhiteListService whiteListService;

    @Autowired
    private CaptchaService captchaService;

    /**
     * Token校验
     *
     * @param token
     * @return
     */
    @GetMapping("/token/check")
    @ApiOperation("Token校验")
    public ResultResponseMsg checkToken(String token) {
        if (StringUtils.isEmpty(token)) {
            throw new BasePublishException(CommonErrorConstants.PARAM_ERROR);
        }
        UserInfo userInfo = userTokenService.getUserInfoByToken(token);
        if (null == userInfo) {
            throw new BasePublishException(CommonErrorConstants.HTTP_TOKEN);
        }
        return ResultResponseMsg.buildSuccessResultMsg(userInfo.getUsername());
    }

    /**
     * URL白名单(SecurityFilter无需安全校验)
     *
     * @return
     */
    @GetMapping("/whiteList")
    @ApiOperation("白名单列表")
    public ResultResponseMsg whiteList() {
        return ResultResponseMsg.buildSuccessResultMsg(whiteListService.queryValidWhiteList());
    }

    /**
     * 获取验证码服务
     *
     * @param httpSession
     * @return
     */
    @GetMapping("/captcha/get")
    @ApiOperation("获取验证码")
    public ResultResponseMsg getCaptcha(HttpSession httpSession) {
        String captcha = captchaService.getCaptcha(httpSession.getId());
        return ResultResponseMsg.buildSuccessResultMsg(captcha);
    }
}